import { Component, OnInit } from '@angular/core'
import { DatatableComponent } from '@swimlane/ngx-datatable/release'
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'
import { Router, ActivatedRoute } from '@angular/router'

declare var $: any
@Component({
  selector: 'sa-regional-manager',
  templateUrl: './regional-manager.component.html'
})
export class RegionalManagerComponent implements OnInit {
  tableData: any = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 0 //分页当前页
  pageSize: number = 10 //分页每页条数
  searchKey: string = '' //搜索keyword
  btnData: any = []
  userAdd: boolean = false
  userDelete: boolean = false
  areaId: string = '' // 负责省份
  areaName: string = ''
  areaList: any = [] // 用户类型列表
  inputApi: string = 'maintenance/reginlist.html'
  inputApi2: string = ''
  addRowData: any = {}
  belongArea: string = '' // 所属区域
  stuffList: any[] = [] // 添加责任人列表
  areaList2:any; // 所属区域数据
  stuffSelectData: any = {
    userId: '',
    name: '',
    userName: '',
    phone: ''
  }

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  //省份
  regionSelected(data) {
    this.areaId = data.companyId || ''
    this.areaName = data.companyName
  }
  //区域
  areaSelected(data) {
    this.belongArea = data.id || ''
  }
  //初始化钩子函数
  ngOnInit() {
    this.initBtn()
    this.initAreaList()
    this.load()
    this.initAllUser()
    this.initArea().then(() => {
      this.selectAreaName()
    })
  }

  //拉取
  initAllUser() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('user/getAllUserList.html', null).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            var obj = {
              id: userList[i].id,
              name: userList[i].name,
              userName: userList[i].userName,
              phone: userList[i].phone,
              text: ''
            }
            let tempStr = `${userList[i].name} - ${userList[i].userName}`
            if (userList[i].phone) tempStr = tempStr + ' - ' + userList[i].phone
            obj.text = tempStr
            selectdata[i] = obj
          }
        }
        that.stuffList = selectdata
        resolve(selectdata)
      })
    })
  }

  //初始化select2 选项
  selectUserName() {
    const that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#managerSelect')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: this.stuffList //为Select添加数据
          })
          .on('select2:select', function (e) {
            const data = e.params.data
            that.stuffSelectData.userId = data.id
            that.stuffSelectData.name = data.name
            that.stuffSelectData.userName = data.userName
            that.stuffSelectData.phone = data.phone
          })
      })
    })
  }


  initArea() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('area/areaList.html', null).subscribe(data => {
        if (data.success) {
          var areaList = data.data
          var selectdata = []
          for (var i = 0; i < areaList.length; i++) {
            var obj = {
              id: areaList[i].id,
              name: areaList[i].name,
              text: areaList[i].name,
            }
            selectdata[i] = obj
          }
        }
        console.log(selectdata, 'selectdata')
        that.areaList2 = selectdata
        resolve(selectdata)
      })
    })
  }

  	//擦除所选的所属区域值
	delAreaName(){
		this.belongArea = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#areaNameSelect2').val("");
		$("#select2-areaNameSelect2-container").empty();
		$("#select2-areaNameSelect2-container").attr("title","");
		$("#select2-areaNameSelect2-container").prepend(str);
		this.load();
	}

  selectAreaName(){
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				$("#areaNameSelect2").select2({
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
            data: this.areaList2,
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.belongArea = data.id;
		        });
			})
		})
	}

  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }

  // 区域列表
  initAreaList() {
    this.jsonApiService.http('role/userTypeList.html', {}).subscribe(data => {
      if (data.success) {
        for (let index = 0; index < data.data.length; index++) {
          const element = data.data[index]
          element.text = element.userTypeName
          element.id = element.userType
        }
        this.areaList = data.data
      }
    })
  }
  //刷新
  refresh() {
    this.curPage = 1
    this.load()
  }
  //get权限按钮数据
  initBtn() {
    this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_outsource-management:regional-manager')))
    if (!this.btnData) {
      return
    }
    for (let item of this.btnData) {
      if (item.sourceKey === 'regional-manager:addBtn' && item.parentId) {
        this.userAdd = true
      }
      if (item.sourceKey === 'regional-manager:delBtn' && item.parentId) {
        this.userDelete = true
      }
    }
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.searchKey = common.stringTrim(this.searchKey)
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        name: this.searchKey,
        area: this.areaId,
        belongArea: this.belongArea
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('areaManager/list.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      }
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }

  // 添加负责人
  addManager(modal, row) {
    this.delManagerSelect()
    const that = this
    this.addRowData = row
    modal.show()
    setTimeout(function () {
      System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
        System.import('assets/js/select2-zh-CN.js').then(() => {
          that.clearSelect($('#managerSelect')) //清除Select中的数据
          that.selectUserName()
        })
      })
    }, 100)
  }

  //清空区域 select 组建
  clearSelect(obj) {
    obj.empty()
    obj.prepend("<option value=''>请选择</option>")
  }

  //关闭
  closeViewModal(modal) {
    modal.hide()
  }

  viewManagerSubmit(modal) {
    if (!this.stuffSelectData.name) {
      this.jsonApiService.message('请先选择负责人信息')
      return
    }
    var reqdata = {
      opType: '1',
      areaId: this.addRowData.areaCode,
      ...this.stuffSelectData
    }
    const queryStr = 'param=' + JSON.stringify(reqdata)

    this.jsonApiService.http('areaManager/update.html', queryStr).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.load()
        modal.hide()
      }
    })
  }

  //擦除用户所选值
  delManagerSelect() {
    this.stuffSelectData.userId = ''
    this.stuffSelectData.name = ''
    this.stuffSelectData.userName = ''
    this.stuffSelectData.phone = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    const str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#managerSelect').val('')
    $('#select2-managerSelect-container').empty()
    $('#select2-managerSelect-container').attr('title', '')
    $('#select2-managerSelect-container').prepend(str)
  }

  //表格删除用户
  del_user(row) {
    this.jsonApiService.confirm_message('此操作将永久解除关联负责人信息,确认继续操作?').then(() => {
      const reqdata = {
        opType: '2',
        areaId: row.areaCode
      }
      const queryStr = 'param=' + JSON.stringify(reqdata)
      this.jsonApiService.http('areaManager/update.html', queryStr).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }

  detailTableData: any[] = []

  showAreaManagerDetail(row: any, modal) {
    if (!row.maintenancePoint || row.maintenancePoint.length === 0) {
      return
    }
    modal.show()
    const reqdata = 'points=' + row.maintenancePoint.join(',')
    const that = this
    this.jsonApiService.http('areaManager/detail.html', reqdata).subscribe(data => {
      that.jsonApiService.message(data.message)
      if (data.success) {
        data.data.forEach(el => {
          el.companyStr = ''
          if (el.companyArrays && el.companyArrays.length > 0) {
            const temp = el.companyArrays.map(el => el.companyName)
            el.companyStr = temp.join(',')
          }
          el.employeeInfo = ''
          if (el.employee && el.employee.length > 0) {
            const temp = el.employee.map(el => `${el.name}-${el.phone}`)
            el.employeeInfo = temp.join(',')
          }
        })
        that.detailTableData = data.data
      }
    })
  }
}
